package com.example.service.impl;

import com.example.mapper.*;
import com.example.pojo.*;
import com.example.service.ProductService;
import com.example.utils.ExcelUtils;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private BookMenuMapper bookMenuMapper;
    @Autowired
    private UserAreaMapper userAreaMapper;
    @Autowired
    private LabelMapper labelMapper;
    @Autowired
    private ProductAreaMapper productAreaMapper;
    @Autowired
    private AreaMapper areaMapper;
    @Autowired
    private UserMapper userMapper;

    private int countProduct;
    private int countProductArea;
    private int countUser;
    private List<Product> productList;
    private List<ProductArea> productAreaList;
    private double[] discounts={0.6,0.65,0.7,0.75,0.8,0.9};
    private double[] oldBookDiscounts={0,0.05,0.1,0.15,0.2,0.3,0.4};

    @Override
    public String importBookstoreProduct(String originalPath,Long userId,boolean isNewBook,double discount) {
        List<BookMenu> bookMenuList = ExcelUtils.readExcel(originalPath, BookMenu.class);
        if(bookMenuList==null){
            return "文件不存在";
        }
        int noBookNum=0;
        countProduct=0;
        countProductArea=0;
        productList=new ArrayList<>();
        productAreaList=new ArrayList<>();
        //获得当前代理对象
        ProductServiceImpl proxy= (ProductServiceImpl) AopContext.currentProxy();
        for (BookMenu bookMenu : bookMenuList) {
            String isbn = bookMenu.getIsbn();
            if(isbn==null){
                continue;
            }
            List<BookMenu> bookMenuList1 = bookMenuMapper.selectByIsbn(isbn);
            if(bookMenuList1.size()==0){
                noBookNum++;
                System.out.println(bookMenu.getIsbn());
                continue;
            }
            if(bookMenuList1.size()==1){
                Product product = fillProduct(bookMenuList1.get(0), userId,isNewBook,discount);
                productList.add(product);
                if(productList.size()%1000==0){
                    proxy.batchSave();
                }
                continue;
            }
            BookMenu bookMenu2=bookMenuList1.get(0);
            for (BookMenu menu : bookMenuList1) {
                if(bookMenu.getPrice()!=null&&menu.getPrice()>=(bookMenu.getPrice()-2)&&menu.getPrice()<=(bookMenu.getPrice()+2)){
                    bookMenu2=menu;
                    break;
                }
                if(menu.getPrice()<bookMenu2.getPrice()){
                    bookMenu2=menu;
                }
            }
            Product product = fillProduct(bookMenu2, userId,isNewBook,discount);
            productList.add(product);
            if(productList.size()%1000==0){
                proxy.batchSave();
            }
        }
        if(productList.size()>0){
            proxy.batchSave();
        }
        return "成功（插入商品表"+countProduct+"条，插入商品区域表"+countProductArea+"条，没找到书目"+noBookNum+"条）";
    }

    @Override
    public String importLeadBook(String originalPath, String poiPath, boolean isNewBook, double discount) {
        List<BookMenu> bookMenuList = ExcelUtils.readExcel(originalPath, BookMenu.class);
        List<Poi> poiList = ExcelUtils.readExcel(poiPath, Poi.class);
        if(bookMenuList==null||poiList==null){
            return "文件不存在";
        }
        countProduct=0;
        countProductArea=0;
        productList=new ArrayList<>();
        productAreaList=new ArrayList<>();
        //获得当前代理对象
        ProductServiceImpl proxy= (ProductServiceImpl) AopContext.currentProxy();
        Random random=new Random();
        int n=0;
        int m=0;
        try {
            for (Poi poi : poiList) {
                if(poi.getUserId()==null||poi.getUserId()==-3){
                    continue;
                }
                Set<BookMenu> bookMenus=new HashSet<>();
                n=random.nextInt(18)+8;
                while (bookMenus.size()<n){
                    bookMenus.add(bookMenuList.get(random.nextInt(500)));
                }
                for (BookMenu bookMenu : bookMenus) {
//                    BookMenu bookMenu1 = bookMenuMapper.selectById(bookMenu.getId());
                    Product product = fillProduct(bookMenu, Long.valueOf(poi.getUserId()),isNewBook,discount);
                    productList.add(product);
                }
                m++;
                if(m%60==0){
                    proxy.batchSave();
                }
            }
            if(productList.size()>0){
                proxy.batchSave();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "成功（插入商品表"+countProduct+"条，插入商品区域表"+countProductArea+"条）";
    }

    @Override
    public String importBookstoreLeadBook(String poiPath, String jiaofuPath, String doubanPath, String picturePath
            , boolean isNewBook, double discount) { //除了大学书店
        List<Poi> poiList = ExcelUtils.readExcel(poiPath, Poi.class);
        List<BookMenu> pictureList = ExcelUtils.readExcel(picturePath, BookMenu.class);
        List<BookMenu> jiaofuList = ExcelUtils.readExcel(jiaofuPath, BookMenu.class);
        List<BookMenu> doubanList = ExcelUtils.readExcel(doubanPath, BookMenu.class);
        if(poiList==null||pictureList==null||jiaofuList==null||doubanList==null){
            return "文件不存在";
        }
        countProduct=0;
        countProductArea=0;
        productList=new ArrayList<>();
        productAreaList=new ArrayList<>();
        //获得当前代理对象
        ProductServiceImpl proxy= (ProductServiceImpl) AopContext.currentProxy();
        Random random=new Random();
        int n=0;
        int m=0;
        try {
            for (Poi poi : poiList) {
                if(poi.getUserId()==null||poi.getUserId()==-3||(poi.getCategory()!=null&&poi.getCategory()==2)){
                    continue;
                }
                Set<BookMenu> bookMenus=new HashSet<>();
                n=random.nextInt(41)+10;
                if(poi.getCategory()==null){ //独立书店
                    while (bookMenus.size()<n){
                        bookMenus.add(doubanList.get(random.nextInt(248)));
                    }
                }else if(poi.getCategory()==3){ //小学，教辅
                    while (bookMenus.size()<n){
                        bookMenus.add(jiaofuList.get(random.nextInt(200)));
                    }
                }else { //绘本
                    while (bookMenus.size()<n){
                        bookMenus.add(pictureList.get(random.nextInt(500)));
                    }
                }
                for (BookMenu bookMenu : bookMenus) {
//                    BookMenu bookMenu1 = bookMenuMapper.selectById(bookMenu.getId());
                    Product product = fillProduct(bookMenu, Long.valueOf(poi.getUserId()),isNewBook,discount);
                    productList.add(product);
                }
                m++;
                if(m%40==0){
                    proxy.batchSave();
                }
            }
            if(productList.size()>0){
                proxy.batchSave();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "成功（插入商品表"+countProduct+"条，插入商品区域表"+countProductArea+"条）";
    }

    @Override
    public String importUniversityBookstoreLeadBook(String poiPath, String kaoyanPath, String kaogongPath, String zsbPath
            , String doubanPath, boolean isNewBook, double discount) {
        List<Poi> poiList = ExcelUtils.readExcel(poiPath, Poi.class);
        List<BookMenu> kaoyanList = ExcelUtils.readExcel(kaoyanPath, BookMenu.class);
        List<BookMenu> kaogongList = ExcelUtils.readExcel(kaogongPath, BookMenu.class);
        List<BookMenu> zsbList = ExcelUtils.readExcel(zsbPath, BookMenu.class);
        List<BookMenu> doubanList = ExcelUtils.readExcel(doubanPath, BookMenu.class);
        if(poiList==null||kaoyanList==null||kaogongList==null||zsbList==null||doubanList==null){
            return "文件不存在";
        }
        countProduct=0;
        countProductArea=0;
        productList=new ArrayList<>();
        productAreaList=new ArrayList<>();
        //获得当前代理对象
        ProductServiceImpl proxy= (ProductServiceImpl) AopContext.currentProxy();
        Random random=new Random();
        int n=0;
        int m=0;
        int num=0;
        try {
            for (Poi poi : poiList) {
                if(poi.getUserId()==null||poi.getUserId()==-3){
                    continue;
                }
                Set<BookMenu> bookMenus=new HashSet<>();
                n=random.nextInt(15)+10;
                if(poi.getCategory()==1){ //本科学校
                    while (bookMenus.size()<n){
                        bookMenus.add(kaoyanList.get(random.nextInt(95)));
                    }
                }else{ //专科学校
                    while (bookMenus.size()<n){
                        bookMenus.add(zsbList.get(random.nextInt(100)));
                    }
                }
                n=random.nextInt(14)+10;
                num=0;
                while (num<n){
                    bookMenus.add(kaogongList.get(random.nextInt(99)));
                    num++;
                }
                n=random.nextInt(14)+10;
                num=0;
                while (num<n){
                    bookMenus.add(doubanList.get(random.nextInt(248)));
                    num++;
                }
                for (BookMenu bookMenu : bookMenus) {
//                    BookMenu bookMenu1 = bookMenuMapper.selectById(bookMenu.getId());
                    Product product = fillProduct(bookMenu, Long.valueOf(poi.getUserId()),isNewBook,discount);
                    productList.add(product);
                }
                m++;
                if(m%20==0){
                    proxy.batchSave();
                    m=0;
                }
            }
            if(productList.size()>0){
                proxy.batchSave();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "成功（插入商品表"+countProduct+"条，插入商品区域表"+countProductArea+"条）";
    }

    @Override
    public String updateOldBookToNewBook(String poiPath) {
        List<Poi> poiList = ExcelUtils.readExcel(poiPath, Poi.class);
        if(poiList==null){
            return "文件不存在";
        }
        List<User> userList=new ArrayList<>();
        List<Product> productList1=new ArrayList<>();
        Random random=new Random();
        //获得当前代理对象
        ProductServiceImpl proxy= (ProductServiceImpl) AopContext.currentProxy();
        countProduct=0;
        countUser=0;
        double totalPrice=0.0;
        try {
            for (Poi poi : poiList) {
                if(poi.getUserId()==null||poi.getUserId()==-3){
                    continue;
                }
                double discount = discounts[random.nextInt(discounts.length)];
                User user = userMapper.selectByUserId(poi.getUserId());
                user.setBookStoreDiscount(discount);
                userList.add(user);
                List<Product> productList2 = productMapper.selectByUserId(poi.getUserId());
                for (Product product : productList2) {
//                    BookMenu bookMenu = bookMenuMapper.selectById(Math.toIntExact(product.getBookId()));
                    totalPrice=product.getPrice()+product.getCash();
                    product.setCash(totalPrice*discount);
                    product.setPrice(totalPrice-product.getCash());
                    product.setBookCondition(1); //新书
                    productList1.add(product);
                }
                if(userList.size()%30==0){
                    proxy.batchUpdate(userList,productList1);
                    userList.clear();
                    productList1.clear();
                }
            }
            if(userList.size()>0){
                proxy.batchUpdate(userList,productList1);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "成功（更新商品表"+countProduct+"条，更新用户表"+countUser+"条）";
    }

    @Override
    public String updateOldBook(String poiPath) {
        List<Poi> poiList = ExcelUtils.readExcel(poiPath, Poi.class);
        if(poiList==null){
            return "文件不存在";
        }
        Random random=new Random();
        double totalPrice=0.0;
        int n=0;
        int m=0;
        List<Product> products=new ArrayList<>();
        try {
            for (Poi poi : poiList) {
                if(poi.getUserId()==null||poi.getUserId()==-3){
                    continue;
                }
                List<Product> productList1 = productMapper.selectByUserId(poi.getUserId());
                for (Product product : productList1) {
                    double oldBookDiscount = oldBookDiscounts[random.nextInt(oldBookDiscounts.length)];
                    totalPrice=product.getPrice()+product.getCash();
                    product.setCash(totalPrice*oldBookDiscount);
                    product.setPrice(totalPrice-product.getCash());
                    products.add(product);
                }
                m++;
                if(m%50==0){
                    n += productMapper.batchUpdate(products);
                    products.clear();
                }
            }
            if(products.size()>0){
                n += productMapper.batchUpdate(products);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("更新到用户："+m+"个");
        return "成功（更新商品表："+n+"条）";
    }

    @Transactional
    public void batchUpdate(List<User> userList, List<Product> productList) {
        int u = userMapper.batchUpdate(userList);
        int p = productMapper.batchUpdate(productList);
        countUser += u;
        countProduct += p;
    }

    @Transactional
    public void batchSave() {
        int n = productMapper.batchInsert(productList);
        for (Product product1 : productList) {
            ProductArea productArea = fillProductArea(product1.getProductId(), Math.toIntExact(product1.getAreaId()));
            productAreaList.add(productArea);
        }
        int m = productAreaMapper.batchInsert(productAreaList);
        countProduct += n;
        countProductArea += m;
        productList.clear();
        productAreaList.clear();
    }

    private Product fillProduct(BookMenu bookMenu,Long userId,boolean isNewBook,double discount){
        Product product = new Product();
        product.setUserId(userId);
        product.setProductType(0);
        product.setProductCategory(0);
        product.setProductName(bookMenu.getName());
        product.setPrice(bookMenu.getPrice()-bookMenu.getPrice()*discount);
        product.setCash(bookMenu.getPrice()*discount);
        if(isNewBook){
            //新书
            product.setBookCondition(1);
        }else {
            //旧书
            product.setBookCondition(0);
        }
        product.setDescription(bookMenu.getContentValidity());
        product.setSmallImg(bookMenu.getImg()!=null?bookMenu.getImg():"");
        product.setStatus(1);
        product.setAreaId(userAreaMapper.selectByUserIdAndAreaType(userId,0).getVillageId());
        product.setBookId(Long.valueOf(bookMenu.getId()));
        Label label = labelMapper.selectByLabelName(bookMenu.getType());
        if(label!=null){
            product.setLabelId(label.getId());
        }else {
            product.setLabelId(0L);
        }
        product.setAppearance(fillAppearance(bookMenu.getPublishTime()));
        product.setProductGroup("0-"+bookMenu.getId());
        product.setDelFlag(0);
        product.setCreateBy(userId);
        return product;
    }

    private ProductArea fillProductArea(Long productId,Integer villageId){
        Integer areaId = areaMapper.selectById(villageId).getParentId();
        Integer cityId = areaMapper.selectById(areaId).getParentId();
        Integer provinceId = areaMapper.selectById(cityId).getParentId();

        ProductArea productArea = new ProductArea();
        productArea.setProductId(productId);
        productArea.setProvinceId(Long.valueOf(provinceId));
        productArea.setCityId(Long.valueOf(cityId));
        productArea.setAreaId(Long.valueOf(areaId));
        productArea.setVillageId(Long.valueOf(villageId));
        return productArea;
    }

    private Integer fillAppearance(String publishTime){
        if(publishTime==null){
            return 8;
        }
        if(publishTime.startsWith("202")){
            return 9;
        }else if(publishTime.startsWith("201")){
            return 9;
        }else if(publishTime.startsWith("200")){
            return 8;
        }else if(publishTime.startsWith("199")){
            return 7;
        }else {
            return 6;
        }
    }
}
